/**
 * Created by houyefeng on 2015-02-12.
 */
package com.emar.adx.yiqifa.util;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * 基于MyBaits实现的枚举类型转换工具类。
 *
 * @author houyefeng
 * @version 4.0.0
 * @see org.apache.ibatis.type.BaseTypeHandler
 *
 * @since 4.0.0 2015-02-12
 */
public class EnumHandler<X, T extends Enum<X>> extends BaseTypeHandler<T> {
    private final static Logger log = LoggerFactory.getLogger(EnumHandler.class);
    private Class<T> type;
    private final Map<X, T> enumMap;

    public EnumHandler(Class<T> type) {
        if (type == null)
            throw new IllegalArgumentException("type argument cannot be null");
        this.type = type;
        T[] enums = type.getEnumConstants();
        if (enums == null)
            throw new IllegalArgumentException(type.getSimpleName()
                    + " does not represent an enum type.");
        this.enumMap = new HashMap<X, T>();
        loadEnumMap(enums);
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException {
        ps.setObject(i, parameter.getValue());
        log.debug("jdbcType:" + jdbcType.getClass());
    }

    @Override
    public T getNullableResult(ResultSet rs, String columnName) throws SQLException {
        X value = (X) rs.getObject(columnName);
        T status = this.enumMap.get(value);
        if (null == status) {
            log.warn("Unknown enum type:" + value + ",refer to " + this.enumMap);
        }
        return status;
    }

    @Override
    public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        X value = (X) rs.getObject(columnIndex);
        T status = this.enumMap.get(value);
        if (null == status) {
            log.warn("Unknown enum type:" + value + ",refer to " + this.enumMap);
        }
        return status;
    }

    @Override
    public T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        X value = (X) cs.getObject(columnIndex);
        T status = this.enumMap.get(value);
        if (null == status) {
            log.warn("Unknown enum type:" + value + ",refer to " + this.enumMap);
        }
        return status;
    }

    private void loadEnumMap(T[] enums) {
        for (T status : enums) {
            this.enumMap.put(status.getValue(), status);
        }
    }
    protected Map<X, T> getEnumMap() {
        return this.enumMap;
    }
}
